// 国际化模块

// 语言类型
export type Language = 'zh-CN' | 'en-US'

// 翻译键类型
export type TranslationKey = string

// 翻译值类型
export type TranslationValue = string | Record<string, any>

// 翻译配置接口
export interface TranslationConfig {
  language: Language
  fallbackLanguage: Language
  translations: Record<Language, Record<TranslationKey, TranslationValue>>
  pluralization?: Record<Language, (count: number) => string>
}

// 国际化管理器类
class I18nManager {
  private config: TranslationConfig
  private currentLanguage: Language
  private fallbackLanguage: Language

  constructor(config: TranslationConfig) {
    this.config = config
    this.currentLanguage = config.language
    this.fallbackLanguage = config.fallbackLanguage
  }

  // 设置当前语言
  setLanguage(language: Language): void {
    this.currentLanguage = language
    // 保存到本地存储
    uni.setStorageSync('i18n_language', language)
  }

  // 获取当前语言
  getCurrentLanguage(): Language {
    return this.currentLanguage
  }

  // 从本地存储恢复语言设置
  restoreLanguage(): void {
    const savedLanguage = uni.getStorageSync('i18n_language') as Language
    if (savedLanguage && this.isValidLanguage(savedLanguage)) {
      this.currentLanguage = savedLanguage
    }
  }

  // 验证语言是否有效
  private isValidLanguage(language: string): language is Language {
    return ['zh-CN', 'en-US'].includes(language)
  }

  // 获取翻译文本
  t(key: TranslationKey, params?: Record<string, any>): string {
    const translation = this.getTranslation(key)

    if (typeof translation === 'string') {
      return this.interpolate(translation, params)
    }

    return key
  }

  // 获取复数形式翻译
  tPlural(
    key: TranslationKey,
    count: number,
    params?: Record<string, any>
  ): string {
    const translation = this.getTranslation(key)

    if (typeof translation === 'object' && translation !== null) {
      const pluralKey = this.getPluralKey(count)
      const pluralTranslation = translation[pluralKey]

      if (typeof pluralTranslation === 'string') {
        return this.interpolate(pluralTranslation, { ...params, count })
      }
    }

    return this.t(key, { ...params, count })
  }

  // 获取翻译对象
  private getTranslation(key: TranslationKey): TranslationValue {
    // 尝试从当前语言获取
    let translation = this.config.translations[this.currentLanguage]?.[key]

    // 如果当前语言没有，尝试从备用语言获取
    if (!translation) {
      translation = this.config.translations[this.fallbackLanguage]?.[key]
    }

    // 如果还是没有，返回键名
    if (!translation) {
      console.warn(`Translation missing for key: ${key}`)
      return key
    }

    return translation
  }

  // 获取复数键
  private getPluralKey(count: number): string {
    const pluralization = this.config.pluralization?.[this.currentLanguage]
    if (pluralization) {
      return pluralization(count)
    }

    // 默认复数规则
    return count === 1 ? 'one' : 'other'
  }

  // 插值替换
  private interpolate(template: string, params?: Record<string, any>): string {
    if (!params) return template

    return template.replace(/\{\{(\w+)\}\}/g, (match, key) => {
      return params[key] !== undefined ? String(params[key]) : match
    })
  }

  // 检查是否有翻译
  hasTranslation(key: TranslationKey): boolean {
    return !!this.getTranslation(key)
  }

  // 获取所有可用的翻译键
  getAvailableKeys(): TranslationKey[] {
    const currentTranslations =
      this.config.translations[this.currentLanguage] || {}
    return Object.keys(currentTranslations)
  }

  // 获取支持的语言列表
  getSupportedLanguages(): Language[] {
    return Object.keys(this.config.translations) as Language[]
  }

  // 更新翻译配置
  updateTranslations(
    language: Language,
    translations: Record<TranslationKey, TranslationValue>
  ): void {
    this.config.translations[language] = {
      ...this.config.translations[language],
      ...translations,
    }
  }

  // 获取翻译统计
  getTranslationStats(): Record<Language, number> {
    const stats: Record<string, number> = {}

    Object.keys(this.config.translations).forEach((lang) => {
      stats[lang] = Object.keys(
        this.config.translations[lang as Language]
      ).length
    })

    return stats
  }
}

// 默认翻译配置
const defaultTranslations: Record<
  Language,
  Record<TranslationKey, TranslationValue>
> = {
  'zh-CN': {
    // 通用
    'common.confirm': '确认',
    'common.cancel': '取消',
    'common.save': '保存',
    'common.delete': '删除',
    'common.edit': '编辑',
    'common.add': '添加',
    'common.search': '搜索',
    'common.loading': '加载中...',
    'common.error': '错误',
    'common.success': '成功',
    'common.warning': '警告',
    'common.info': '信息',

    // 导航
    'nav.home': '首页',
    'nav.profile': '个人中心',
    'nav.settings': '设置',
    'nav.about': '关于',

    // 登录注册
    'auth.login': '登录',
    'auth.register': '注册',
    'auth.logout': '退出登录',
    'auth.username': '用户名',
    'auth.password': '密码',
    'auth.confirmPassword': '确认密码',
    'auth.email': '邮箱',
    'auth.phone': '手机号',
    'auth.captcha': '验证码',
    'auth.forgotPassword': '忘记密码',
    'auth.rememberMe': '记住我',

    // 表单验证
    'validation.required': '此字段为必填项',
    'validation.email': '请输入有效的邮箱地址',
    'validation.phone': '请输入有效的手机号',
    'validation.password': '密码长度至少8位',
    'validation.confirmPassword': '两次输入的密码不一致',
    'validation.minLength': '长度不能少于{{min}}位',
    'validation.maxLength': '长度不能超过{{max}}位',

    // 错误信息
    'error.network': '网络连接失败',
    'error.server': '服务器错误',
    'error.unauthorized': '未授权访问',
    'error.forbidden': '访问被拒绝',
    'error.notFound': '资源不存在',
    'error.timeout': '请求超时',

    // 时间
    'time.today': '今天',
    'time.yesterday': '昨天',
    'time.tomorrow': '明天',
    'time.week': '周',
    'time.month': '月',
    'time.year': '年',

    // 数量
    'count.items': {
      one: '{{count}} 项',
      other: '{{count}} 项',
    },
    'count.users': {
      one: '{{count}} 个用户',
      other: '{{count}} 个用户',
    },
  },

  'en-US': {
    // Common
    'common.confirm': 'Confirm',
    'common.cancel': 'Cancel',
    'common.save': 'Save',
    'common.delete': 'Delete',
    'common.edit': 'Edit',
    'common.add': 'Add',
    'common.search': 'Search',
    'common.loading': 'Loading...',
    'common.error': 'Error',
    'common.success': 'Success',
    'common.warning': 'Warning',
    'common.info': 'Info',

    // Navigation
    'nav.home': 'Home',
    'nav.profile': 'Profile',
    'nav.settings': 'Settings',
    'nav.about': 'About',

    // Auth
    'auth.login': 'Login',
    'auth.register': 'Register',
    'auth.logout': 'Logout',
    'auth.username': 'Username',
    'auth.password': 'Password',
    'auth.confirmPassword': 'Confirm Password',
    'auth.email': 'Email',
    'auth.phone': 'Phone',
    'auth.captcha': 'Captcha',
    'auth.forgotPassword': 'Forgot Password',
    'auth.rememberMe': 'Remember Me',

    // Validation
    'validation.required': 'This field is required',
    'validation.email': 'Please enter a valid email address',
    'validation.phone': 'Please enter a valid phone number',
    'validation.password': 'Password must be at least 8 characters',
    'validation.confirmPassword': 'Passwords do not match',
    'validation.minLength': 'Length must be at least {{min}} characters',
    'validation.maxLength': 'Length must not exceed {{max}} characters',

    // Errors
    'error.network': 'Network connection failed',
    'error.server': 'Server error',
    'error.unauthorized': 'Unauthorized access',
    'error.forbidden': 'Access denied',
    'error.notFound': 'Resource not found',
    'error.timeout': 'Request timeout',

    // Time
    'time.today': 'Today',
    'time.yesterday': 'Yesterday',
    'time.tomorrow': 'Tomorrow',
    'time.week': 'Week',
    'time.month': 'Month',
    'time.year': 'Year',

    // Count
    'count.items': {
      one: '{{count}} item',
      other: '{{count}} items',
    },
    'count.users': {
      one: '{{count}} user',
      other: '{{count}} users',
    },
  },
}

// 复数规则配置
const pluralizationRules: Record<Language, (count: number) => string> = {
  'zh-CN': () => 'other',
  'en-US': (count: number) => (count === 1 ? 'one' : 'other'),
}

// 创建国际化管理器实例
export const i18n = new I18nManager({
  language: 'zh-CN',
  fallbackLanguage: 'en-US',
  translations: defaultTranslations,
  pluralization: pluralizationRules,
})

// 初始化时恢复语言设置
i18n.restoreLanguage()

// 便捷方法
export const t = i18n.t.bind(i18n)
export const tPlural = i18n.tPlural.bind(i18n)
export const setLanguage = i18n.setLanguage.bind(i18n)
export const getCurrentLanguage = i18n.getCurrentLanguage.bind(i18n)

export default i18n
